<?php
namespace Addons\TimedTask\Controller\Api;
use Addons\QyWechat\Services\QyWechatApi;
use Models\BaseModel as Model;
use Addons\TimedTask\Helper;
require_once(DOXCX_FRAME_PATH . 'fun/library/QyWxCypto/WXBizMsgCrypt.php');

/**
 * 发送待办事项提醒
 */
class SendBacklogRemind extends \BaseController
{
	public function index(){
		set_time_limit(0);
        $res = ['code'=>'ok'];
		$backlogs = (new Model('qy_user_backlog'))->where(['send_status'=>0])->list_all();
		foreach ($backlogs as $key => $backlog) {
			$wid = $backlog->wid;
            if($backlog->send_time <= time()){
            	$messenger = $this->getMessenger($wid);
            	if(!$messenger) continue;
            	$dynamic = (new Model('qy_et_dynamic'))->find($backlog->dynamic_id);
            	$user = (new \Model('qy_user_list'))->find($dynamic->user_id);
            	$et = (new Model('qy_externalcontact_list'))->find(['wid'=>$wid,'external_userid'=>$dynamic->external_userid,'user_id'=>$dynamic->user_id]);
            	$url = Helper::getInstance()->get_http_server_name().'/Addons/CustomerPortrait/H5/Portrait/customer_info.html?etUserId='.$dynamic->external_userid.'&wid='.$wid.'&userId='.$dynamic->user_id;
            	$content = '@'.$user->name.',你收到一条关于客户 ['.$et->name.'] 的提醒事件<br>提醒内容: "'.$backlog->content.'"<br><a href="'.$url.'">点击查看客户详情</a>';
            	$messenger->toUser($user->userid)->send($content);
            	$back =  (new Model('qy_user_backlog'))->find($backlog->id);
            	$back->send_status = 1;
            	$back->save();
            }
		}
		return json_encode($res);
	}

	private function getMessenger($wid){
		$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
		$messenger = null;
		if($qyConfig->corp_id){
		 	//发送应用消息
		 	$QyWechatApi = QyWechatApi::getInstance();
            $sendConfig = (new Model('qy_message_send_config'))->find(['wid'=>$wid]);
            if($sendConfig->agent_id && $sendConfig->secret){
                $app = $QyWechatApi->get_qy_agent_app($qyConfig->corp_id,$sendConfig->agent_id,$sendConfig->secret);
                $messenger = $app->messenger->ofAgent($sendConfig->agent_id);
            }
        }
        return $messenger;
	}
}